﻿using System;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Net;
using System.Text; 

namespace SoufunData
{
    public class Common
    {
        public static string UrlEncode(string str)
        {
            
            StringBuilder sb = new StringBuilder();
            byte[] byStr = Encoding.GetEncoding("gbk").GetBytes(str); //默认是System.Text.Encoding.Default.GetBytes(str)
            for (int i = 0; i < byStr.Length; i++)
            {
                sb.Append(@"%" + Convert.ToString(byStr[i], 16));
            }
            return (sb.ToString());
        }


        public static string UrlEncodeHanzi(string url)
        {
            byte[] bs = Encoding.GetEncoding("GB2312").GetBytes(url);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < bs.Length; i++)
            {
                if (bs[i] < 128)
                    sb.Append((char)bs[i]);
                else
                {
                    sb.Append("%" + bs[i++].ToString("x").PadLeft(2, '0'));
                    sb.Append("%" + bs[i].ToString("x").PadLeft(2, '0'));
                }
            }
            return sb.ToString();
        }  

        public static string GetHtmlTextByUrl(string strUrl)
        {
            string strRet = null;
            try
            {
                WebClient myWebClient = new WebClient();
                myWebClient.Encoding = Encoding.GetEncoding("gb2312");
                strUrl = UrlEncodeHanzi(strUrl);
                strRet = myWebClient.DownloadString(strUrl);
                //Console.WriteLine(strRet);
            }
            catch (Exception e)
            {
                strRet = "";
            }
            return strRet;
        }

        public static bool DownloadFileByUrl(string httpUrl, string savePath)
        {
            try
            {
                HttpWebRequest myrq = (HttpWebRequest)WebRequest.Create(httpUrl);
                HttpWebResponse myrp = (HttpWebResponse)myrq.GetResponse();
                long totalBytes = myrp.ContentLength;

                Stream st = myrp.GetResponseStream();
                Stream so = new FileStream(savePath, FileMode.Create);
                long totalDownloadedByte = 0;
                byte[] by = new byte[1024];
                int osize = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    System.Windows.Forms.Application.DoEvents();
                    so.Write(by, 0, osize);
                    osize = st.Read(by, 0, (int)by.Length);
                }

                so.Close();
                st.Close();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }


        //加载Excel    
        public static DataSet LoadDataFromExcel(string filePath)
        {
            DataSet ds = null;
            try
            {
                string strConn;
                strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";               
                OleDbConnection OleConn = new OleDbConnection(strConn);
                OleConn.Open();
                String sql = "SELECT * FROM  [Sheet1$]";//可更改Sheet名称，比如sheet2，等等    

                OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn);
                DataSet OleDsExcle = new DataSet();
                OleDaExcel.Fill(OleDsExcle, "Sheet1");
                OleConn.Close();
                ds = OleDsExcle;
                return ds;
            }
            catch (Exception err)
            {
                ds = null;
            }
            try
            {
                string strConn;              
                strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=YES\"";
                OleDbConnection OleConn = new OleDbConnection(strConn);
                OleConn.Open();
                String sql = "SELECT * FROM  [Sheet1$]";//可更改Sheet名称，比如sheet2，等等    
                OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn);
                DataSet OleDsExcle = new DataSet();
                OleDaExcel.Fill(OleDsExcle, "Sheet1");
                OleConn.Close();
                return OleDsExcle;
            }
            catch (Exception err)
            {
                return null;
            }
        }

        public static string Doc2Text(string docFileName)
        {
            try
            {
                //实例化COM
                Microsoft.Office.Interop.Word.ApplicationClass wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
                object fileobj = docFileName;
                object nullobj = System.Reflection.Missing.Value;
                //打开指定文件（不同版本的COM参数个数有差异，一般而言除第一个外都用nullobj就行了）
                Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Open(ref fileobj, ref nullobj, ref nullobj,
                    ref nullobj, ref nullobj, ref nullobj,
                    ref nullobj, ref nullobj, ref nullobj,
                    ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj
                    );
                //取得doc文件中的文本
                string outText = doc.Content.Text;
                //关闭文件
                doc.Close(ref nullobj, ref nullobj, ref nullobj);
                //关闭COM
                wordApp.Quit(ref nullobj, ref nullobj, ref nullobj);
                //返回
                return outText;
            }
            catch (Exception ex)
            {
                return null;
            }
         
        } 


    }
}
